<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2020/11/27
 * Time: 9:56
 */

namespace app\index\controller;


use app\service\TaskService;
use think\App;
use think\Db;

class BizTask extends Common
{
    public function __construct(?App $app = null)
    {
        parent::__construct($app);
        # 将过期未完成的任务状态改为  4
        BizTask::ChangeExpirationStatus();
    }

    /**
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @content 门店任务列表
     */
    function taskList()
    {
        # 查询该门店的领取的任务列表
        $info = Db::table('cooperative_task_list tl')
            ->field('tl.id,t.title,t.explain_info,tl.task_num,concat(t.cycle,"天") cycle,tl.reward_balance,tl.complete_num,tl.status,over_time,
            case t.type 
                when 1 then \'办理会员数量\'
                when 2 then \'销售额\'
                when 3 then \'服务车辆次数\'
                when 4 then \'好评数量\'
                when 5 then \'办理会员金额\'
            end typeInfo,
            case t.type 
                when 1 then \'名\'
                when 2 then \'元\'
                when 3 then \'次\'
                when 4 then \'次\'
                when 5 then \'元\'
            end typeMark
                            ')
            ->join('cooperative_task t', 't.id=tl.task_id')
            ->where(array('biz_id' => $this->bizId))
            ->where("tl.status != 3 and tl.status != 4")
            ->order('status asc')
            ->select();
        $time = date('Y-m-d H:i:s');
        if (!empty($info)) {
            foreach ($info as $k => $v) {
                if ($v['status'] == 1) {
                    $info[$k]['cycle'] = timediff($time, $v['over_time'], false)['day'].'天';
                }
                if($info[$k]['cycle']=='0天'){
                    $info[$k]['cycle']='1天';
                }
            }
        }
        # 查询该门店未领取的任务列表
        $notReceived = Db::table('cooperative_task')
            ->field('id,title,explain_info,num task_num,concat(cycle,"天") cycle,balance reward_balance,0 complete_num,0 status,
            case type 
                when 1 then \'办理会员数量\'
                when 2 then \'销售额\'
                when 3 then \'服务车辆次数\'
                when 4 then \'好评数量\'
                when 5 then \'办理会员金额\'
            end typeInfo,
            case type 
                when 1 then \'名\'
                when 2 then \'元\'
                when 3 then \'次\'
                when 4 then \'次\'
                when 5 then \'元\'
            end typeMark')
            ->where("start_time <= '" . $time . "' and end_time > '" . $time . "'")
            ->where("id not in 
            (select task_id from cooperative_task_list where (status = 1 or status = 2) and biz_id = " . $this->bizId . ")")
            ->where("id not in 
            (select task_id from cooperative_task_list ct left join cooperative_task c on ct.task_id=c.id
             where (status = 3 or status = 4) and is_loop=1 and biz_id = '" . $this->bizId . "')")
            ->select();
        $arr = array_merge($info, $notReceived);
        return array('status' => true, 'msg' => '查询成功', 'info' => $arr);
    }

    /**
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @content 领取任务
     */
    function CollectTask()
    {
        #任务id
        $taskId = input('post.id');
        if (empty($taskId)) {
            return array('status' => false, 'msg' => '任务id为空');
        }
        # 查询任务详情
        $time = date('Y-m-d H:i:s');
        $taskInfo = Db::table('cooperative_task')
            ->field('num,cycle,balance')
            ->where(array('id' => $taskId))
            ->where("start_time <= '" . $time . "' and end_time > '" . $time . "'")
            ->find();
        if (empty($taskInfo)) {
            return array('status' => false, 'msg' => '任务已过期');
        }
        # 添加领取任务列表
        Db::table('cooperative_task_list')
            ->insert(array(
                'task_id' => $taskId,
                'biz_id' => $this->bizId,
                'create_time' => $time,
                'over_time' => date('Y-m-d H:i:s', strtotime('+ ' . $taskInfo['cycle'] . ' days')),
                'task_num' => $taskInfo['num'],
                'complete_num' => 0,
                'status' => 1,
                'reward_balance' => $taskInfo['balance']
            ));
        return array('status' => true, 'msg' => '任务领取成功');
    }

    /**
     * @return array
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     * @content 领取任务奖励
     */
    function ReceiveRewards()
    {
        # 接收任务id
        $task_id = input('post.task_id');
        if (empty($task_id)) {
            return array('status' => false, 'msg' => '任务id为空');
        }
        # 查询任务详情
        $taskInfo = Db::table('cooperative_task_list')
            ->field('status,reward_balance')
            ->where(array('id' => $task_id))
            ->find();
        if (empty($taskInfo)) {
            return array('status' => false, 'msg' => '任务信息为空');
        }
        # 判断状态
        if ($taskInfo['status'] == 1) {
            return array('status' => false, 'msg' => '任务正在进行中');
        }
        if ($taskInfo['status'] == 3) {
            return array('status' => false, 'msg' => '任务奖励已领取过');
        }
        if ($taskInfo['status'] == 4) {
            return array('status' => false, 'msg' => '任务已过期');
        }
        # 领取奖励,加余额
        Db::table('biz')->where(array('id' => $this->bizId))->setInc('account_balance', $taskInfo['reward_balance']);
        # 修改状态
        Db::table('cooperative_task_list')->where(array('id' => $task_id))
            ->update(array('status' => 3, 'reward_time' => date('Y-m-d H:i:s')));
        # 增加补贴记录,13,合作店完成任务奖励
        addSubsidy(array("subsidy_type" => 13, "subsidy_number" => $taskInfo['reward_balance'],'member_id'=>0, "biz_id" => $this->bizId,'pid'=>$task_id));
        return array('status' => true, 'msg' => '奖励领取成功');
    }

    /**
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     * @content 将过期未完成的任务状态改为  4
     */
    static function ChangeExpirationStatus()
    {
        Db::table('cooperative_task_list')
            ->where("status = 1 and over_time <= '" . date('Y-m-d H:i:s') . "' and complete_num<task_num")
            ->update(array('status' => 4));
    }

    /**
     * @param $task_type
     * @param $biz_id
     * @param $complete_num
     * @return array
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     * @content 完成任务
     */
    static function FinishTask($task_type, $biz_id, $complete_num)
    {
        if (empty($task_type) or empty($biz_id)) {
            return array('status' => false, 'msg' => '参数存在空值');
        }
        # 查询该门店是否存在该类型的正在进行中的任务
        $taskInfo = Db::table('cooperative_task_list tl')
            ->field('tl.id,task_num,complete_num')
            ->join('cooperative_task t', 't.id=tl.task_id')
            ->where(array('biz_id' => $biz_id, 'status' => 1, 'type' => $task_type))
            ->find();
        if (empty($taskInfo)) {
            return array('status' => false, 'msg' => '没有可完成任务');
        }
        if ($complete_num < 0) {
            $complete_num = -$complete_num;
        }
        # 判断状态
        $complete = $taskInfo['complete_num'] + $complete_num;
        if ($taskInfo['task_num'] <= $complete) {
            $arr = array('status' => 2, 'complete_num' => $complete, 'completion_time' => date('Y-m-d H:i:s'));
        } else {
            $arr = array('complete_num' => $complete);
        }
        Db::table('cooperative_task_list')->where(array('id' => $taskInfo['id']))->update($arr);
        return array('status' => true, 'msg' => '距离完成任务又近了一步');
    }

    /**
     * @return array|false[]
     * @context 获取每日任务
     */
    function getsDayTask(){
        return TaskService::todayBizTask($this->bizId);
    }
}
